package DieSiedler;

import java.awt.Component;
import java.util.ArrayList;

public class Animator extends Thread {
	
	private boolean active;
	private Component c;
	private ArrayList<AnimationInterface> animations;
	private GcCaller gc;
	
	Animator(Component c, AnimationInterface[] ai){
		this.active = false;
		this.c = c;
		
		animations = new ArrayList<AnimationInterface>();
		if(ai != null){
			for(int i=0; i<ai.length; i++){
				animations.add(ai[i]);
			}
		}		
	}
	
	public void setActive(boolean option){
    	active = option;
    	if(active && !this.isAlive()){
    		this.start();
    		gc = new GcCaller();
			gc.start();
    	}
    }
	
	public boolean isActive(){
		return active;
	}
	
	synchronized public void add(AnimationInterface ai){
		animations.add(ai);
	}
	
	synchronized public void remove(AnimationInterface ai){
		animations.remove(ai);
	}
	
	synchronized private void move(){
		for (AnimationInterface ai: animations){
			if(ai != null){
				ai.nextImage();
			}
		}
	}
	
	public void run(){
    	int runs = 0;	
		
        while(true){
        	while(active){
        		runs++;
        		
        		move();
	            
	            c.repaint();
	            
	            if(runs > 200){
	            	//if(gc != null){
	            		gc.ceanUp();
	            	//}	            	
	            	runs = 0;
	            }
	            
	            try{
	                sleep(50);
	            }
	            catch(InterruptedException e){
	                
	            }
        	}
        	
        	try{
                sleep(500);
            }
            catch(InterruptedException e){
                
            }        	
        }
    }

}
